package com.wans.guli.common.exception;

import com.wans.guli.common.exception.em.ExceptionInfoEnum;
import com.wans.guli.common.utils.R;
import lombok.extern.slf4j.Slf4j;
import org.springframework.validation.BindException;
import org.springframework.validation.FieldError;
import org.springframework.validation.ObjectError;
import org.springframework.web.bind.MethodArgumentNotValidException;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.RestControllerAdvice;

import java.util.HashMap;
import java.util.List;

@RestControllerAdvice
@Slf4j
public class GlobalExceptionHandle {

    /**
     * 处理MethodArgumentNotValidException异常 - 参数校验失败错误
     *
     * @param e 错误
     * @return R
     */
    @ExceptionHandler(MethodArgumentNotValidException.class)
    public R handleException(MethodArgumentNotValidException e) {

        HashMap<String, String> errorInfo = new HashMap<>();
        List<ObjectError> allErrors = e.getBindingResult().getAllErrors();
        allErrors.forEach(error -> {
            if (error instanceof FieldError)
                errorInfo.put(((FieldError) error).getField(), error.getDefaultMessage());
            else
                errorInfo.put(error.getObjectName(), error.getDefaultMessage());
        });

        errorInfo.values().forEach(log::error);
        return R.error(ExceptionInfoEnum.VALID_EXCEPTION, errorInfo);
    }

    /**
     * 处理BindException异常
     *
     * @param e 错误
     * @return R
     */
    @ExceptionHandler(BindException.class)
    public R handleException(BindException e) {
        log.error(e.getMessage(), e);
        return R.error(ExceptionInfoEnum.BIND_EXCEPTION);
    }

    /**
     * 处理RuntimeException异常
     *
     * @param e 异常
     * @return R
     */
    @ExceptionHandler(RuntimeException.class)
    public R handleException(RuntimeException e) {
        log.error(e.getMessage(), e);
        return R.error(ExceptionInfoEnum.UNKNOWN_EXCEPTION).put("msg", e.getMessage());
    }

    /**
     * 处理Exception异常
     *
     * @param e 异常
     * @return R
     */
    @ExceptionHandler(Exception.class)
    public R handleException(Exception e) {
        log.error(e.getMessage(), e);
        return R.error(ExceptionInfoEnum.UNKNOWN_EXCEPTION);
    }

    /**
     * 处理Throwable异常
     *
     * @param throwable 错误
     * @return R
     */
    @ExceptionHandler(Throwable.class)
    public R handleException(Throwable throwable) {
        log.error(throwable.getMessage(), throwable);
        return R.error(ExceptionInfoEnum.UNKNOWN_EXCEPTION);
    }
}
